/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.controller.admin;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.lang.stream.StringInputStream;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.request.admin.ServiceRequestMessage;
import cn.easyplatform.messages.vos.admin.*;
import cn.easyplatform.spi.service.AdminService;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.type.ServiceType;
import cn.easyplatform.web.contexts.Contexts;
import cn.easyplatform.web.dialog.MessageBox;
import cn.easyplatform.web.service.ServiceLocator;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.lang3.RandomStringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.zkoss.lang.Objects;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zkmax.zul.Scrollview;
import org.zkoss.zul.*;
import org.zkoss.zul.theme.Themes;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/11/25 10:07
 * @Modified By:
 */
public class TemplateController implements Composer<Component>, EventListener {

    private Tree tree;

    private Textbox name;

    private Textbox desp;

    private Textbox query;

    private Iframe loginPage;

    private Iframe mainPage;

    private TemplateVo templateVo;

    private Object current;

    private ProjectVo pv;

    private Button themesBtn;

    private Scrollview themesView;

    private Popup pop;

    private static Vlayout currentLayout;

    private java.util.List<String> ids;
    private List<String> names;

    @Override
    public void doAfterCompose(Component comp) throws Exception {

        for (Component c : comp.getFellows()) {
            if (c.getId().equals("tree")) {
                tree = (Tree) c;
                tree.addEventListener(Events.ON_SELECT, this);
            } else if (c instanceof Button) {
                if (c.getId().equals("themesBtn"))
                    themesBtn = (Button) c;
                c.addEventListener(Events.ON_CLICK, this);
            } else if (c instanceof Textbox) {
                if (c.getId().equals("name"))
                    name = (Textbox) c;
                else if (c.getId().equals("desp"))
                    desp = (Textbox) c;
                else if (c.getId().equals("query"))
                    query = (Textbox) c;
                c.addEventListener(Events.ON_CHANGE, this);
            } else if (c.getId().equals("loginPage"))
                loginPage = (Iframe) c;
            else if (c.getId().equals("mainPage"))
                mainPage = (Iframe) c;
            else if (c.getId().equals("themesView"))
                themesView = (Scrollview) c;
            else if (c.getId().equals("themesPop"))
                pop = (Popup) c;
        }
        AdminService as = ServiceLocator.lookup(AdminService.class);
        IResponseMessage<?> resp = as.getService(new ServiceRequestMessage(new ServiceVo("", "", ServiceType.PROJECT, 0)));
        pv = (ProjectVo) resp.getBody();
        resp = as.getConfig(new SimpleRequestMessage("template"));
        if (resp.isSuccess()) {
            templateVo = (TemplateVo) resp.getBody();
            load();
        } else {
            comp.detach();
            MessageBox.showMessage(resp);
        }

        List<String> lists = new ArrayList<>();
        for (String themeName : Themes.getThemes()) {
            if (themeName.endsWith("_c") || themeName.equals("sapphire") || themeName.equals("breeze") || themeName.equals("silvertail"))
                lists.add(themeName);
        }
        String[] id = new String[]{"Aquamarine", "atrovirens_c", "Aurora", "Blueberry", "Emerald", "Iceblue", "Lavender",
                "Marigold", "Montana", "Mysterious", "Office", "Olive", "Poppy", "Ruby", "Space"};
        String[] nameList = new String[]{Labels.getLabel("theme.name.color.aquamarine"), Labels.getLabel("theme.name.color.atrovirens_c"),
                Labels.getLabel("theme.name.color.aurora"), Labels.getLabel("theme.name.color.blueberry"), Labels.getLabel("theme.name.color.emerald"),
                Labels.getLabel("theme.name.color.iceblue"), Labels.getLabel("theme.name.color.lavender"), Labels.getLabel("theme.name.color.marigold"),
                Labels.getLabel("theme.name.color.montana"), Labels.getLabel("theme.name.color.mysterious"), Labels.getLabel("theme.name.color.office"),
                Labels.getLabel("theme.name.color.olive"), Labels.getLabel("theme.name.color.poppy"), Labels.getLabel("theme.name.color.ruby"),
                Labels.getLabel("theme.name.color.space")};
        ids = Arrays.asList(id);
        names = Arrays.asList(nameList);
        Collections.sort(lists);
        if (lists != null || lists.size() > 0) {
            Div contentDiv = new Div();
            contentDiv.setHflex("1");
            contentDiv.setStyle("display: flex;flex-direction: row;flex-wrap: wrap;min-width:164px;justify-content: flex-start;");
            themesView.appendChild(contentDiv);
            for (int index = 0; index < lists.size(); index++) {
                String displayName = Themes.getDisplayName(lists.get(index));
                Integer showIndex = ids.indexOf(displayName.split(" ")[0]);
                if (showIndex >= 0) {
                    ThemesCell(lists.get(index), displayName.split(" ")[0], contentDiv);
                }
            }
        }


    }

    private void load() {
        if (templateVo.getPortlets() != null && !templateVo.getPortlets().isEmpty()) {
            for (PortletVo pv : templateVo.getPortlets())
                createNode(pv);
        }
        onSelectHome("ajax");
    }

    private Treeitem createNode(PortletVo pv) {
        Treeitem ti = new Treeitem();
        ti.setSelectable(false);
        ti.setValue(pv);
        Treerow tr = new Treerow();
        tr.appendChild(new Treecell(pv.getName()));
        tr.appendChild(new Treecell(pv.getDesp()));
        A deleteBtn = new A(Labels.getLabel("button.delete"));
        deleteBtn.addEventListener(Events.ON_CLICK, this);
        deleteBtn.setIconSclass("z-icon-trash");
        Treecell cell = new Treecell();
        cell.appendChild(deleteBtn);
        tr.appendChild(cell);
        ti.appendChild(tr);
        if (pv.getDevices() == null)
            pv.setDevices(new ArrayList<>());
        if (pv.getDevices().isEmpty()) {//如果为空预设对象
            DeviceMapVo dv = new DeviceMapVo();
            dv.setType("ajax");
            pv.getDevices().add(dv);
            dv = new DeviceMapVo();
            dv.setType("mil");
            pv.getDevices().add(dv);
        } else if (pv.getDevices().size() == 1) {//如果只有一个先创建其它类型对象
            DeviceMapVo dv = new DeviceMapVo();
            dv.setType(pv.getDevices().get(0).getType().equals("ajax") ? "mil" : "ajax");
            pv.getDevices().add(dv);
        }
        Treechildren tc = new Treechildren();
        for (DeviceMapVo dv : pv.getDevices()) {
            Treeitem tm = new Treeitem();
            tm.setValue(dv.getType());
            tr = new Treerow();
            Treecell treecell = new Treecell(dv.getType().equals("ajax") ? Labels.getLabel("admin.project.device.ajax") : Labels.getLabel("admin.project.device.phone"));
            treecell.setIconSclass(tm.getValue().equals("ajax") ? "z-icon-laptop h5" : "z-icon-tablet h5");
            treecell.setSpan(3);
            tr.appendChild(treecell);
            tm.appendChild(tr);
            tc.appendChild(tm);
        }
        ti.appendChild(tc);
        tree.getTreechildren().appendChild(ti);
        return ti;
    }

    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getTarget() == tree)
            onSelectPortlet();
        else if (event.getTarget() instanceof A)
            onDelete(event);
        else if (event.getName().equals(Events.ON_CHANGE)) {
            onSetValue(event);
        } else {
            String id = event.getTarget().getId();
            if (id.equals("create"))
                onCreate();
            else if (id.equals("save"))
                onSave(event);
            else if (id.equals("selectLogin"))
                onSelectTemplate(event);
            else if (id.equals("selectMain"))
                onSelectTemplate(event);
            else if (id.equals("editLogin"))
                onEditLogin(event);
            else if (id.equals("editMain"))
                onEditMain(event);
            else if (id.equals("laptop")) {
                onSelectHome("ajax");
            } else if (id.equals("mobile"))
                onSelectHome("mil");
            else if (id.equals("load")) {
                AdminService as = ServiceLocator.lookup(AdminService.class);
                IResponseMessage<?> resp = as.getModel(new SimpleRequestMessage(new ModelVo(Contexts.getEnv().getProjectId(), "template")));
                if (!resp.isSuccess())
                    MessageBox.showMessage(resp);
                else {
                    templateVo = (TemplateVo) resp.getBody();
                    tree.getTreechildren().getChildren().clear();
                    load();
                }
            } else if (id.equals("files")) {
                onFiles(event);
            } else if (id.equals("themesBtn")) {
                pop.open(themesBtn, "after_start");
            } else if (id.equals("confirm")) {
                String theme = currentLayout.getId();
                pop.close();
                themesBtn.setLabel(theme);
            } else if (event.getTarget() instanceof Vlayout) {
                if (currentLayout != event.getTarget()) {
                    ((Vlayout) event.getTarget()).setSclass("ui-div-selected");
                    currentLayout.setSclass("ui-div-normal");
                    currentLayout = (Vlayout) event.getTarget();
                }
            }

        }
    }

    private void onFiles(Event event) {
        Window win = new Window(Labels.getLabel("admin.template.file"), "normal", true);
        win.setPage(event.getPage());
        win.setHeight("75%");
        win.setWidth("75%");
        win.setMaximizable(true);
        win.setSizable(true);
        win.setPosition("center,top");
        Executions.createComponents("~./admin/files.zul", win, null);
        win.doOverlapped();
    }

    private void onEditMain(Event event) {
        DeviceMapVo dv;
        if (current instanceof PortletVo) {
            Treeitem sel = tree.getSelectedItem();
            PortletVo vo = (PortletVo) current;
            if (vo.getDevices().get(0).getType().equals(sel.getValue())) {
                dv = vo.getDevices().get(0);
            } else {
                dv = vo.getDevices().get(1);
            }
        } else
            dv = (DeviceMapVo) current;
        new EditorDialog(value -> {
            if (!Objects.equals(value, dv.getMainPage())) {
                dv.setMainPage(value);
                showMain(value);
            }
        }, Labels.getLabel("admin.template.edit"), "60%", "75%", "ajax".equals(dv.getType()) ? 2 : 3).showDialog(event.getPage(), "xml",
                dv.getMainPage());
    }

    private void onEditLogin(Event event) {
        DeviceMapVo dv;
        if (current instanceof PortletVo) {
            Treeitem sel = tree.getSelectedItem();
            PortletVo vo = (PortletVo) current;
            if (vo.getDevices().get(0).getType().equals(sel.getValue())) {
                dv = vo.getDevices().get(0);
            } else {
                dv = vo.getDevices().get(1);
            }
        } else
            dv = (DeviceMapVo) current;
        new EditorDialog(value -> {
            if (!Objects.equals(value, dv.getLoginPage())) {
                dv.setLoginPage(value);
                showLogin(value);
            }
        }, Labels.getLabel("admin.template.edit"), "60%", "75%", 1).showDialog(event.getPage(), "xml",
                dv.getLoginPage());
    }

    private void onSelectTemplate(Event event) {
        DeviceMapVo dm = null;
        String type = event.getTarget().getId().endsWith("Login") ? "login" : "main";
        String dir = "";
        if (current instanceof PortletVo) {
            PortletVo vo = (PortletVo) current;
            if (vo.getDevices().get(0).getType().equals(tree.getSelectedItem().getValue())) {
                dm = vo.getDevices().get(0);
            } else {
                dm = vo.getDevices().get(1);
            }
            dir = vo.getName();
        } else
            dm = (DeviceMapVo) current;
        if ("ajax".equals(dm.getType()))
            dir += type.equals("login") ? "d0" : "d1";
        else
            dir += type.equals("login") ? "m0" : "m1";
        final DeviceMapVo dv = dm;
        new TemplateDialog(new PropertySetCallback<String>() {
            @Override
            public void setValue(String value) {
                InputStream input = null;
                try {
                    //解决模板文件是BOM格式无法解析的问题
                    value = IOUtils.toString(input = new BOMInputStream(new StringInputStream(value)), "utf-8");
                    if (type.equals("login")) {
                        dv.setLoginPage(value);
                        showLogin(value);
                    } else {
                        dv.setMainPage(value);
                        showMain(value);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    IOUtils.closeQuietly(input);
                }
            }

            public String getValue() {
                if (type.equals("login"))
                    return dv.getLoginPage();
                else
                    return dv.getMainPage();
            }
        }, "ajax".equals(dm.getType()) ? "Desktop" : "Mobile", type, dir).showDialog(tree.getPage());
    }

    private void onSetValue(Event event) {
        if (event.getTarget() == name) {
            PortletVo vo = (PortletVo) current;
            for (PortletVo v : templateVo.getPortlets()) {
                if (vo != v && name.getValue().equals(v.getName()))
                    throw new WrongValueException(name, Labels.getLabel("common.input.exist", new String[]{Labels.getLabel("debug.header.name")}));
            }
            vo.setName(name.getValue());
            ((Treecell) tree.getSelectedItem().getParentItem().getFirstChild().getFirstChild()).setLabel(vo.getName());
        } else if (event.getTarget() == desp) {
            if (current instanceof PortletVo) {
                PortletVo vo = (PortletVo) current;
                vo.setDesp(desp.getValue());
                ((Treecell) tree.getSelectedItem().getParentItem().getFirstChild().getFirstChild().getNextSibling()).setLabel(vo.getDesp());
            } else {
                DeviceMapVo dm = (DeviceMapVo) current;
                dm.setName(name.getValue());
            }
        } else if (event.getTarget() == query) {
            PortletVo vo = (PortletVo) current;
            vo.setOnInitQuery(query.getValue());
        }
    }

    private void onDelete(final Event evt) {
        Messagebox.show(Labels.getLabel("admin.service.op.confirm",
                new Object[]{Labels.getLabel("button.delete")}), Labels
                        .getLabel("admin.service.op.title"), Messagebox.CANCEL
                        | Messagebox.OK, Messagebox.QUESTION,
                new EventListener<Event>() {
                    @Override
                    public void onEvent(Event event) throws Exception {
                        if (event.getName().equals(Messagebox.ON_OK)) {
                            Treeitem sel = (Treeitem) evt.getTarget().getParent().getParent().getParent();
                            PortletVo pv = sel.getValue();
                            templateVo.getPortlets().remove(pv);
                            sel.detach();
                        }
                    }
                });
    }

    private void onSelectHome(String type) {
        if (loginPage.getFirstChild() != null)
            loginPage.getFirstChild().detach();
        if (mainPage.getFirstChild() != null)
            mainPage.getFirstChild().detach();
        for (DeviceMapVo dm : templateVo.getDevices()) {
            if (type.equals(dm.getType())) {
                showLogin(dm.getLoginPage());
                showMain(dm.getMainPage());
                name.setValue(type);
                desp.setValue(dm.getName());
                if (!Strings.isBlank(dm.getTheme())) {
                    themesBtn.setLabel(dm.getTheme());
                } else if (!Strings.isBlank(pv.getTheme())) {
                    themesBtn.setLabel(pv.getTheme());
                } else {
                    themesBtn.setLabel(Themes.getCurrentTheme());
                }
                name.setDisabled(true);
                query.setDisabled(true);
                query.setValue("");
                current = dm;
                break;
            }
        }
        tree.setSelectedItem(null);
    }

    private void onSelectPortlet() {
        Treeitem sel = tree.getSelectedItem();
        PortletVo vo = sel.getParentItem().getValue();
        if (loginPage.getFirstChild() != null)
            loginPage.getFirstChild().detach();
        if (mainPage.getFirstChild() != null)
            mainPage.getFirstChild().detach();
        name.setValue(vo.getName());
        desp.setValue(vo.getDesp());
        query.setValue(vo.getOnInitQuery());
        query.setDisabled(false);
        name.setDisabled(false);
        if (vo.getDevices().get(0).getType().equals(sel.getValue())) {
            showLogin(vo.getDevices().get(0).getLoginPage());
            showMain(vo.getDevices().get(0).getMainPage());
            if (!Strings.isBlank(vo.getDevices().get(0).getTheme())) {
                themesBtn.setLabel(vo.getDevices().get(0).getTheme());
            } else if (!Strings.isBlank(pv.getTheme())) {
                themesBtn.setLabel(pv.getTheme());
            } else {
                themesBtn.setLabel(Themes.getCurrentTheme());
            }
        } else {
            showLogin(vo.getDevices().get(1).getLoginPage());
            showMain(vo.getDevices().get(1).getMainPage());
            if (!Strings.isBlank(vo.getDevices().get(1).getTheme())) {
                themesBtn.setLabel(vo.getDevices().get(1).getTheme());
            } else if (!Strings.isBlank(pv.getTheme())) {
                themesBtn.setLabel(pv.getTheme());
            } else {
                themesBtn.setLabel(Themes.getCurrentTheme());
            }
        }
        current = vo;
    }

    private void onSave(Event event) {

        if (current instanceof PortletVo) {
            PortletVo vo = (PortletVo) current;
            Treeitem sel = tree.getSelectedItem();
            if (vo.getDevices().get(0).getType().equals(sel.getValue()))
                vo.getDevices().get(0).setTheme(themesBtn.getLabel());
            else
                vo.getDevices().get(1).setTheme(themesBtn.getLabel());
        } else {
            DeviceMapVo dm = (DeviceMapVo) current;
            dm.setTheme(themesBtn.getLabel());
        }

        List<String> temp1 = new ArrayList<>();
        SAXReader reader = new SAXReader();
        try {
            for (DeviceMapVo dm : templateVo.getDevices()) {
                //检查语法是否正确
                if (!Strings.isBlank(dm.getLoginPage()))
                    reader.read(new StringInputStream(dm.getLoginPage()));
                if (!Strings.isBlank(dm.getMainPage()))
                    reader.read(new StringInputStream(dm.getMainPage()));
            }
            if (templateVo.getPortlets() != null) {
                for (PortletVo pv : templateVo.getPortlets()) {
                    if (Strings.isBlank(pv.getName()))
                        throw new WrongValueException(event.getTarget(), Labels.getLabel("common.input.not.empty", new String[]{Labels.getLabel("debug.header.name")}));
                    if (Strings.isBlank(pv.getDesp()))
                        throw new WrongValueException(event.getTarget(), Labels.getLabel("common.input.not.empty", new String[]{Labels.getLabel("debug.header.desc")}));
                    if (temp1.contains(pv.getName()))//检查名称是否有重复
                        throw new WrongValueException(event.getTarget(), Labels.getLabel("common.input.exist", new String[]{Labels.getLabel("debug.header.name")}));
                    DeviceMapVo ajax = pv.getDevices().get(0);
                    DeviceMapVo mil = pv.getDevices().get(1);
                    //检查语法是否正确
                    if (!Strings.isBlank(ajax.getLoginPage()))
                        reader.read(new StringInputStream(ajax.getLoginPage()));
                    if (!Strings.isBlank(ajax.getMainPage()))
                        reader.read(new StringInputStream(ajax.getMainPage()));
                    if (!Strings.isBlank(mil.getLoginPage()))
                        reader.read(new StringInputStream(mil.getLoginPage()));
                    if (!Strings.isBlank(mil.getMainPage()))
                        reader.read(new StringInputStream(mil.getMainPage()));
                    temp1.add(pv.getName());
                }
            }
        } catch (DocumentException e) {
            throw new WrongValueException(event.getTarget(), Labels.getLabel("common.page.fomat", new String[]{e.getMessage()}));
        }
        AdminService as = ServiceLocator.lookup(AdminService.class);
        IResponseMessage<?> resp = as
                .saveProject(new SimpleRequestMessage(templateVo));
        if (!resp.isSuccess())
            MessageBox.showMessage(resp);
        else {
            Button btn = (Button) event.getTarget();
            MessageBox.showInfo(Labels.getLabel("admin.service.op.title"), Labels.getLabel("common.success", new String[]{btn.getLabel()}));
        }
    }

    private void onCreate() {
        if (templateVo.getPortlets() == null)
            templateVo.setPortlets(new ArrayList<>());
        PortletVo pv = new PortletVo();
        templateVo.getPortlets().add(pv);
        Treeitem ti = createNode(pv);
        ((Treeitem) ti.getLastChild().getFirstChild()).setSelected(true);
        name.setValue("");
        desp.setValue("");
        query.setValue("");
        if (loginPage.getFirstChild() != null)
            loginPage.getFirstChild().detach();
        if (mainPage.getFirstChild() != null)
            mainPage.getFirstChild().detach();
        name.setDisabled(false);
        desp.setDisabled(false);
        query.setDisabled(false);
        current = pv;
    }

    private void showLogin(String content) {
        if (Strings.isBlank(content)) {
            loginPage.setSrc(null);
        } else {
            try {
                Document doc = DocumentHelper.parseText(content);
                Node node = doc.selectSingleNode("//@apply");
                if (node != null)//删除apply属性
                    node.getParent().remove(node);
                content = doc.asXML().replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
                String name = RandomStringUtils.randomAlphanumeric(10);
                loginPage.getDesktop().getSession().setAttribute(name, content);
                loginPage.setSrc("/portal?preview=" + name);
            } catch (DocumentException e) {
                throw new WrongValueException(loginPage, Labels.getLabel("common.page.fomat", new String[]{e.getMessage()}));
            }
        }
    }

    private void showMain(String content) {
        if (Strings.isBlank(content)) {
            mainPage.setSrc(null);
        } else {
            try {
                Document doc = DocumentHelper.parseText(content);
                Node node = doc.selectSingleNode("//@apply");
                if (node != null)//删除apply属性
                    node.setText(PreivewLayoutController.class.getName());
                content = doc.asXML().replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
                String name = RandomStringUtils.randomAlphanumeric(10);
                mainPage.getDesktop().getSession().setAttribute(name, content);
                mainPage.setSrc("/portal?preview=" + name);
            } catch (DocumentException e) {
                throw new WrongValueException(loginPage, Labels.getLabel("common.page.fomat", new String[]{e.getMessage()}));
            }
        }
    }

    private void ThemesCell(String themeId, String themeName, Component parentLayout) {
        if (Strings.isBlank(themeName)) {
            Div div = new Div();
            div.setHflex("1");
            parentLayout.appendChild(div);
        } else {
            Integer index = ids.indexOf(themeName);
            Vlayout contentLayout = new Vlayout();
            contentLayout.setSpacing("0");
            contentLayout.setHeight("200px");
            contentLayout.setWidth("164px");
            contentLayout.setStyle("text-align: center;");//;border:#195B40 solid 2px;
            contentLayout.setSclass("ui-div-normal");
            contentLayout.addEventListener(Events.ON_CLICK, this);
            contentLayout.setId(themeId);
            parentLayout.appendChild(contentLayout);

            Div oneDiv = new Div();
            oneDiv.setHeight("15px");
            contentLayout.appendChild(oneDiv);

            Image contentImage = new Image();
            contentImage.setSrc("~./img/theme/" + themeName + ".png");
            contentImage.setHeight("137px");
            contentImage.setWidth("137px");
            contentLayout.appendChild(contentImage);

            Div secondDiv = new Div();
            secondDiv.setHeight("8px");
            contentLayout.appendChild(secondDiv);

            Label contentLabel = new Label();
            contentLabel.setValue(names.get(index));
            contentLabel.setStyle("font-size:12px;border-radius: 14px;padding: 2px 8px;");
            contentLayout.appendChild(contentLabel);

            Div lastDiv = new Div();
            lastDiv.setHeight("8px");
            contentLayout.appendChild(lastDiv);
            String theme = Themes.getCurrentTheme();
            if (theme.equals(themeId)) {
                currentLayout = contentLayout;
                currentLayout.setSclass("ui-div-selected");
            }
        }
    }

}
